package com.baidu.sggc.core.service;

import com.baidu.sggc.entity.vo.FsVo;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.MinioException;

import java.io.InputStream;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class MinioService {

  @Autowired
  private MinioClient minioClient;

  @Value("${minio.bucket-name}")
  private String bucketName;

  public FsVo uploadObject(MultipartFile file) {
    try {
      BucketExistsArgs existsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
      boolean isExist = minioClient.bucketExists(existsArgs);
      if (!isExist) {
        MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(this.bucketName).build();
        minioClient.makeBucket(makeBucketArgs);
      }

      int splitIndex = file.getOriginalFilename().lastIndexOf(".");
      String fileName = file.getOriginalFilename().substring(0, splitIndex);
      String fileExtention = file.getOriginalFilename().substring(splitIndex + 1);
      fileName = file.getOriginalFilename();
      ;
      String objectName = file.getOriginalFilename() + "-" + System.currentTimeMillis() + "." + fileExtention;
      // 上传文件
      ObjectWriteResponse response = minioClient.putObject(
              PutObjectArgs.builder()
                      .bucket(bucketName)
                      .object(objectName)
                      .stream(file.getInputStream(), file.getSize(), -1)
                      .contentType(file.getContentType())
                      .build()
      );
      FsVo fsVo = new FsVo();
      if (response != null) {
        fsVo.setObject(response.object());
        fsVo.setFileName(fileName);
      }
      return fsVo;
    } catch (Exception e) {
      throw new RuntimeException("上传文件失败" + e);
    }
  }

  /**
   * 下载文件
   *
   * @param objectName 对象名称
   */
  public InputStream downloadFile(String objectName) throws Exception {
    GetObjectResponse response = minioClient.getObject(
            GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
    return response;
  }

  /**
   * 删除文件
   *
   * @param objectName 对象名称
   */
  public void deleteFile(String objectName) throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
    // 删除对象
    minioClient.removeObject(
            RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
  }
}
